﻿using System;
using VisionarySystems.Library;
using System.Data;
using System.Data.SqlClient;

namespace VisionarySystems.TimeRegi.Database
{
	public class TimeRegiDatabaseUpdater : DatabaseUpdater
	{
		public TimeRegiDatabaseUpdater(string DataSource, string DatabaseName) : base(DataSource, DatabaseName) { }

		protected override int UpdateToVersion(int VersionNo)
		{
			int NewVersion = VersionNo-1;
			switch (VersionNo)
			{ 
				case 1:
					NewVersion = UpdateToVersion1();
					break;
				default:
					throw new Exception("Unknown CheckDatabaseVersion");
			}
			return NewVersion;
		}

		private int UpdateToVersion1()
		{
			const string SqlCreateSystemInfoTable = @"
			CREATE TABLE SystemInfo (
			VersionNo int not null 
			)";

			m_DatabaseUtils.CreateTable(Conn, SqlCreateSystemInfoTable);

			try
			{
				if (Conn.State != ConnectionState.Open)
					Conn.Open();

				// Add TimeSlotType
				SqlCommand cmdAddTimeSlotType = Conn.CreateCommand();
				cmdAddTimeSlotType.CommandText = "ALTER TABLE TimeSlots ADD TimeSlotType int";
				cmdAddTimeSlotType.ExecuteNonQuery();

				//Update Existing Timeslots
				SqlCommand cmdUpdateTimeSlotType = Conn.CreateCommand();
				cmdUpdateTimeSlotType.CommandText = "UPDATE TimeSlots set TimeSlotType = 1";
				cmdUpdateTimeSlotType.ExecuteNonQuery();

				// Insert VersionNo
				SqlCommand cmdSetVersionNo = Conn.CreateCommand();
				cmdSetVersionNo.CommandText = "Insert into " + SystemTableName + " Values (1)";
				cmdSetVersionNo.ExecuteNonQuery();
			}
			finally
			{
				if (Conn.State == ConnectionState.Open)
					Conn.Close();
			}

			return 1;
		}

	}
}
